<template>
  <view class="u-page">
    <u--form ref="form" labelPosition="top" labelWidth="100%" :labelStyle="labelStyle" :model="form" :rules="rules">
      <u-form-item label="继承权利人身份证正面" prop="idCard1PositiveUrl">
        <u-upload
          accept="image"
          capture="['album', 'camera']"
          width="360"
          height="240"
          name="idCard1PositiveUrl"
          maxCount="1"
          :fileList="idCard1PositiveUrl"
          @afterRead="uploadFile($event, atterUploadCardFile)"
          @delete="deleteFile($event, atterDeleteFile)"
        >
          <image src="../../static/card-positive.png" mode="widthFix" class="card-img"></image>
        </u-upload>
      </u-form-item>
      <u-form-item label="继承权利人身份证反面" prop="idCard1BackUrl">
        <u-upload
          accept="image"
          capture="['album', 'camera']"
          width="360"
          height="240"
          name="idCard1BackUrl"
          maxCount="1"
          :fileList="idCard1BackUrl"
          @afterRead="uploadFile($event, atterUploadCardBack)"
          @delete="deleteFile($event, atterDeleteFile)"
        >
          <image src="../../static/card-back.png" mode="widthFix" class="card-img"></image>
        </u-upload>
      </u-form-item>
      <u-form-item label="继承权利人姓名" prop="name1">
        <u--input v-model="form.name1" required placeholder="请输入继承权利人姓名" clearable></u--input>
      </u-form-item>
      <u-form-item label="继承权利人证件号" prop="idCard1No">
        <u--input v-model="form.idCard1No" required placeholder="请输入继承权利人证件号" clearable></u--input>
      </u-form-item>
	  <u-form-item label="证件有效期" prop="losedDate1">
	    <u--input v-model="form.losedDate1" disabled></u--input>
	  </u-form-item>
      <u-form-item label="集资参与人死亡证明" prop="deathCertificateUrl">
        <u-upload
          accept="image"
          capture="['album', 'camera']"
          width="360"
          height="240"
          name="deathCertificateUrl"
          maxCount="1"
          :fileList="deathCertificateUrl"
          @afterRead="uploadFile($event, atterUploadFile)"
          @delete="deleteFile($event, atterDeleteFile)"
        >
          <image src="../../static/card-dead.png" mode="widthFix" class="card-img"></image>
        </u-upload>
      </u-form-item>
      <!-- <u-form-item label="公证书" prop="authenticAct">
        <u-upload
          accept="image"
          capture="['album', 'camera']"
          width="360"
          height="240"
          name="authenticAct"
          maxCount="3"
          :fileList="authenticAct"
          @afterRead="uploadFile($event, atterUploadMutiFile)"
          @delete="deleteFile($event, atterDeleteMutiFile)"
        >
          <image src="../../static/card-act.png" mode="widthFix" class="card-img"></image>
        </u-upload>
      </u-form-item> -->
      <u-form-item label="与集资参与人关系" prop="relation">
        <u--input v-model="form.relation" required placeholder="请输入与集资参与人关系" clearable></u--input>
      </u-form-item>
      <!-- <u-form-item label="户口()" prop="registeredResidence">
        <u-upload
          accept="image"
          capture="['album', 'camera']"
          width="240"
          height="160"
          name="registeredResidence"
          maxCount="2"
          :fileList="registeredResidence"
          @afterRead="uploadFile($event, atterUploadMutiFile)"
          @delete="deleteFile($event, atterDeleteMutiFile)"
        >
          <image
            v-if="registeredResidence.length === 0"
            src="../../static/card-house-holder.png"
            mode="widthFix"
            class="card-house-img"
          ></image>
          <image
            v-if="registeredResidence.length === 1"
            src="../../static/card-self.png"
            mode="widthFix"
            class="card-house-img"
          ></image>
        </u-upload>
      </u-form-item> -->
	  <!-- <view class="u-flex mt-2">
	    <text class="">手机号码</text>
	  </view>
	  <text class="tip">继承权利人功能正在开发中，请留下您的手机号码，便于联系到您。</text>
	  <view>
	  		  <view class="u-flex mt-2">
	  			  <u--input v-model="form.contactNumber" required placeholder="请输入手机号码" clearable></u--input>
	  		  </view>
	  </view> -->
	  <u-form-item label="住址" prop="address">
	    <pickerAddress @change="addressChange" class="tip">{{form.address == '' ? '点此选择住址' : form.address}}</pickerAddress>
	  </u-form-item>
      <u-form-item class="mt-2">
        <u-row class="w-100" justify="center">
          <u-col span="5" justify="center">
            <u-button shape="circle" @click="toPreSrPage"><view>上一步</view></u-button>
          </u-col>
          <u-col span="1"></u-col>
          <u-col span="5" justify="center">
            <u-button type="primary" shape="circle" @click="confirm"><view>下一步</view></u-button>
          </u-col>
		  <!-- <u-col span="5" justify="center">
		    <u-button type="primary" shape="circle" @click="confirm"><view>确定</view></u-button>
		  </u-col> -->
        </u-row>
      </u-form-item>
    </u--form>
    <!-- <u-row class="mt-4">
      <u-col span="12"><uni-steps :options="stepList" :active="currentStepIndex"></uni-steps></u-col>
    </u-row> -->
	<view>
	  <u-modal :show="tipShow" title="温馨提示">
	    <view>
	      <view class="font-tip">{{ tipText }}</view>
	    </view>
	
	    <u-button slot="confirmButton" @click="tipSubmit" type="success" shape="circle">确定</u-button>
	  </u-modal>
	</view>
	<view>
		<u-modal :show="ttShow" showCancelButton title="温馨提示" @confirm="ttShow = false" @cancel="ttShow = false">
		  <view>
		    <view class="font-tip">{{ ttTipText }}</view>
		  </view>
				<!-- <u-button slot="confirmButton" @click="goSign" type="success" shape="circle">确定</u-button>
				<u-button slot="confirmButton" @click="signTipShow = false" type="success" shape="circle">取消</u-button> -->
		</u-modal>
	</view>
  </view>
</template>

<script>
import { checkIdNumber } from '@/util/validate.js';
import { baseFont, srStepKey } from '@/common/config.js';
import { getAccessToken, idCardOCR, idCardOCRBack } from '@/common/baiduApi.js';
import { pathToBase64 } from 'image-tools';
import { uploadImage } from '@/common/api/common.js';
import { checkSave } from '@/common/api/srRegister.js';
import { checkPhone } from '@/util/validate.js';
import pickerAddress from '@/component/pickerAddress/pickerAddress.vue'

export default {
  components: {
	pickerAddress
  },
  data() {
    return {
      preStep: srStepKey.step1,
      currentStep: srStepKey.step1_5,
      nextStep: srStepKey.step2,
      currentStepIndex: 1,
      labelStyle: { fontSize: baseFont + 'upx', marginBottom: '10upx' },
      idCard1PositiveUrl: [],
      idCard1BackUrl: [],
      deathCertificateUrl: [],
      authenticAct: [],
      registeredResidence: [],
      form: {
        idCard1PositiveUrl: '',
        idCard1FaceUrl: '',
        idCard1FaceBase64: '',
        idCard1BackUrl: '',
        name1: '',
        idCard1No: '',
        deathCertificateUrl: '',
        authenticAct: [],
        relation: '',
        registeredResidence: [],
        copyIdCardNo: '',
		// contactNumber: '',
		address: '',
		losedDate1: ''
      },
      rules: {
        idCard1PositiveUrl: {
          type: 'string',
          required: true,
          message: '请上传继承权利人身份证正面',
          trigger: ['blur'],
        },
        idCard1BackUrl: {
          type: 'string',
          required: true,
          message: '请上传继承权利人身份证反面',
          trigger: ['blur'],
        },
        name1: {
          type: 'string',
          required: true,
          message: '请填写继承权利人姓名',
          trigger: ['blur', 'change'],
        },
        idCard1No: [
          {    
        type: 'string',
            required: true,
            message: '请填写集资参与人证件号',   
         trigger: ['blur', 'change'],
          },
          { validator: checkIdNumber, trigger: ['blur', 'change'] },
        ],
        deathCertificateUrl: {
          type: 'string',
          required: true,
          message: '请上传集资参与人死亡证明',
          trigger: ['blur'],
        },
        authenticAct: {
          type: 'array',
          required: true,
          message: '请上传公证书',
          trigger: ['blur'],
        },
        relation: {
          type: 'string',
          required: true,
          message: '请填写与集资参与人关系',
          trigger: ['blur', 'change'],
        },
        registeredResidence: {
          type: 'array',
          required: false,
          message: '请上传户主页与本人页',
          trigger: ['blur'],
        },
		contactNumber: [
		  {
		    type: 'string',
		    required: true,
		    message: '请填写手机号码',
		    trigger: ['blur', 'change'],
		  },
		  { validator: checkPhone, trigger: ['blur', 'change'] },
		],
		address: {
		  type: 'string',
		  required: true,
		  message: '请选择住址',
		  trigger: ['blur'],
		},
      },
	  tipShow: false,
	  tipText: '您的手机号码，我们已保存，请耐心等待。',
	  ttShow: false,
	  ttTipText: '填报人，既继承权利人，继承公正必须与填报人信息一致。'
    };
  },
  onLoad(options) {
    this.checkSrPage(options);
    this.imageBackShow(['idCard1PositiveUrl', 'idCard1BackUrl', 'deathCertificateUrl']);
    this.mutiImageBackShow(['registeredResidence', 'authenticAct']);
	
	this.ttShow = true;
	
	// this.checkSrPage(options);
	// const { index = {}, step0_5 = {}, step1 = {}, step2 = {}, step1_5 = {} } = this.$getSrInfo(this.idCard);
	// this.form = {
	//   ...this.form,
	//   ...index,
	//   ...step1,
	//   ...step2,
	// };
	// // 办理人逻辑判断
	// if (this.oneself) {
	//   this.cardFaceBase64 = step1.idCardFaceBase64;
	// } else {
	//   this.cardFaceBase64 = step1_5.idCard1FaceBase64;
	//   this.form = {
	//     ...this.form,
	//     ...step1_5,
	//   };
	// }
	// const { resultList = [] } = index;
	// if (resultList.length === 0) {
	//   this.toSrIndex();
	// }
	// // 白名单
	// if (resultList[0].type === 1) {
	//   this.form.caseList=resultList.map(item=>{return {cid:item.cid}})
	// } else if (resultList[0].type === 2 || resultList[0].type === 3) {
	//   this.toSrIndex();
	// } else {
	//   // 数据补录
	//   this.form.caseList=step0_5.resultList
	// }
  },
  methods: {
    async atterUploadCardFile(fileList) {
      this.form.idCard1PositiveUrl = fileList[0].url;
      this.$refs.form.validateField('idCard1PositiveUrl');
      const imageBase64 = await pathToBase64(fileList[0].thumb);
      const accessToken = await getAccessToken();
      const { data } = await idCardOCR(imageBase64, accessToken);
      if (data.idcard_number_type == -1) {
        this.form.idCard1FaceBase64 = '';
        return;
      }
      const idCard = data.words_result['公民身份号码'].words;
      const name = data.words_result['姓名'].words;
      // 识别出证件保存
      this.form.idCard1No = idCard;
      this.form.copyIdCardNo = idCard;
      this.$refs.form.validateField('idCard1No');
      this.form.name1 = name;
      this.$refs.form.validateField('name1');
      // 识别图片保存
      const photo = data.photo;
      const { fileName } = await uploadImage(photo);
      this.form.idCard1FaceBase64 = photo;
      this.form.idCard1FaceUrl = fileName;
      uni.hideLoading()
    },
	// 上传身份证反面
	async atterUploadCardBack(fileList) {
	  this.form.idCard1BackUrl = fileList[0].url;
	  this.$refs.form.validateField('idCard1BackUrl');
	  
	  const imageBase64 = await pathToBase64(fileList[0].thumb);
	  const accessToken = await getAccessToken();
	  const { data } = await idCardOCRBack(imageBase64, accessToken);
	  
	  const ld = data.words_result['失效日期'];
	  if (!ld) {
		  uni.$u.toast('请上传身份证证件照国徽面！');
		  this.form.idCard1BackUrl = '';
		  return;
	  }
	  const qf = data.words_result['签发日期'];
	  const loseDate = ld.words;
	  const qfDate = qf.words;
	  if (loseDate) {
		  let start = qfDate.substring(0,4) + '.' + qfDate.substring(4, 6) + '.' + qfDate.substring(6, 8) ;
		  let end = loseDate.substring(0,4) + '.' + loseDate.substring(4, 6) + '.' + loseDate.substring(6, 8) ;
		  this.form.losedDate1 = start + ' 至 ' + end;
	    let newDate = new Date();
		let year = newDate.getFullYear();
		let month = newDate.getMonth().toString().padStart(2,0);
		let day = newDate.getDay().toString().padStart(2,0);
		let dt = year +  month  + day;
		if (parseInt(loseDate) <= parseInt(dt)) {
			this.form.idCard1BackUrl = '';
			uni.$u.toast('您的证件已过期！');
			uni.hideLoading();
			return;
		}
	  }
	  uni.hideLoading();
	},
    confirm() {
      let that = this;
      that.$refs.form.validate().then(res => {
        if (that.form.idCard1FaceBase64 == '' || that.form.idCard1FaceBase64 == null) {
          uni.$u.toast('证件检测不合格，请重新上传证件，证件多余边不要太大，也不要缺失！');
          return;
        }
        if (that.form.copyIdCardNo != that.form.idCard1No) {
          uni.$u.toast('输入的证件号与检测结果不符，请确认！');
          return;
        }
        this.toNextSrPage(this.idCard);
		
		// checkSave(that.form).then(res => {
		//   const cid=this.form.caseList.map(item=>item.cid).join(',')
		//   that.toSrResult(res.data.state, res.data.reason, that.idCard,cid);
		//   // that.tipShow = true;
		// });
      });
    },
	tipSubmit() {
			  this.tipShow = false;
			  this.toSrIndex();
	},
	addressChange(data) {
		this.form.address = data.data.join('')
	},
  },
};
</script>

<style lang="scss" scoped>
.active-color {
  color: $u-primary;
}
</style>
